package org.fire.mina;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.fire.FireApplication;

import android.util.Log;

public class MinaConnectorHandler extends IoHandlerAdapter {
	private static final String TAG = "MinaConnectorHandler";

	@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		if (Log.isLoggable(TAG, Log.DEBUG)) {
			Log.d(TAG, "catch exception:" + cause.getMessage());
		}
	}

	@Override
	public void sessionCreated(IoSession session) throws Exception {
		if (Log.isLoggable(TAG, Log.DEBUG)) {
			Log.d(TAG, session + " created");
		}
	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		if (Log.isLoggable(TAG, Log.DEBUG)) {
			Log.d(TAG, session + " opened");
		}
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		if (Log.isLoggable(TAG, Log.DEBUG)) {
			Log.d(TAG, session + " closed");
		}
	}

	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {

		if (Log.isLoggable(TAG, Log.DEBUG)) {
			Log.d(TAG, "Message got: " + message.toString());
		}

		FireApplication app = (FireApplication) session
				.getAttribute("application");
		MinaMessageHandler handler = app.getMessageHandler();
		String msgStr = message.toString();
		if (null != handler) {
			new MinaMessageHandlerThread(handler, msgStr).start();
		}
	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus status)
			throws Exception {

		if (Log.isLoggable(TAG, Log.DEBUG)) {
			Log.d(TAG, "IDLE " + session.getIdleCount(status));
		}
	}
}